<template>
    <ul class="alphabet">
      <li class="item" 
        v-for="item of letters" 
        :key="item"
        :ref="item"
        @touchstart.prevent="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
        @click="handleLetterClick">{{item}}</li>
    </ul>
</template>
<script>
export default {
  name: 'Alphabet',
    props: {
      cities: Object
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop  // A距离顶部的高度  注意-性能优化1：首次获取数据，数据未获取到是空，获取到后会再次执行updated钩子函数
  },
  methods: {
    handleLetterClick (e) {
        this.$emit('change', e.target.innerText)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {  
      if (this.touchStatus) { // 可以拖动的时候
        // 注意-性能优化2：函数节流 每次移动做一个16毫秒的延迟
        if (this.timer) {
            clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 79 // 手指的信息:手指距离顶部的距离- 搜索title的79
            // console.log(touchY)
          const index = Math.floor((touchY - this.startY) / 20) // 向下去整，得到对应字母下标
            // console.log(index)
          if(index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        },16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    },
   }
}
</script>
<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .alphabet //字母表
    display: flex
    flex-direction: column
    justify-content: center
    position: absolute 
    top: 1.58rem
    right: 0
    bottom: 0
    width: .4rem
    .item
      line-height: .4rem
      text-align: center
      color: $bgColor
</style>

